//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

namespace Preflight.ServiceModel.Security
{
    using System;
    using System.Linq;
    using System.Net.Http;
    using System.Security.Principal;
    using System.Web;

    internal class RoleBasedRequestAuthorization : IPreflightRequestAuthorization
    {
        private readonly PreflightServiceOptions serviceOptions;

        public RoleBasedRequestAuthorization(PreflightServiceOptions serviceOptions)
        {
            this.serviceOptions = serviceOptions;
        }

        public bool IsAuthorized(HttpRequestMessage request)
        {
            if (this.serviceOptions.Roles == null)
            {
                Log.LogVerbose("Roles property is null. Denying request");
                return false;
            }

            if (this.serviceOptions.Roles.Any() == false)
            {
                Log.LogVerbose("Roles property is empty. Denying request");
                return false; 
            }

            var principal = this.GetPrincipal(request);

            if (principal == null)
            {
                Log.LogError("Could not obtain principal. This request will be denied");
                return false;
            }

            if (this.IsAuthorized(principal))
            {
                return true;
            }

            Log.LogVerbose("User is not in any of the allowed roles. Authorization failed");
            return false;
        }

        protected virtual IPrincipal GetPrincipal(HttpRequestMessage request)
        {
            try
            {
                if (HttpContext.Current != null && HttpContext.Current.User != null)
                {
                    Log.LogVerbose("Using HttpContext to get principal. User is: {0}", HttpContext.Current.User.Identity.Name);
                    return HttpContext.Current.User;
                }

                var securityMessageProperty = request.GetSecurityMessageProperty();
                if (securityMessageProperty == null)
                {
                    Log.LogVerbose("Security message property is null.");
                    return null;
                }

                if (securityMessageProperty.ServiceSecurityContext == null)
                {
                    Log.LogVerbose("Service security context is null");
                    return null;
                }

                if (securityMessageProperty.ServiceSecurityContext.IsAnonymous)
                {
                    Log.LogVerbose("Login was anonymous. Cannot get windows identity");
                    return null;
                }

                return new WindowsPrincipal(securityMessageProperty.ServiceSecurityContext.WindowsIdentity);
            }
            catch (Exception exception)
            {
                Log.LogError("Failed to obtain windows identity because of the following error: {0}", exception);
                return null;
            }
        }

        private bool IsAuthorized(IPrincipal principal)
        {
            foreach (var role in this.serviceOptions.Roles)
            {
                Log.LogVerbose("Checking if user is in role: {0}", role);
                if (principal.IsInRole(role))
                {
                    Log.LogVerbose("User is in role: {0}. Authorization passed", role);
                    return true;
                }
            }

            return false;
        }

        public static IPreflightRequestAuthorization Create(PreflightServiceOptions options)
        {
            return new RoleBasedRequestAuthorization(options);
        }
    }
}
